package cn.com.cetccst.appstore.ui.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.model.CategoryModel;
import cn.com.cetccst.appstore.databinding.AdapterCategoryListBinding;
import cn.com.cetccst.uicomponents.binding.recyclerview.SimpleDataBindingAdapter;

public class CategoryListAdapter extends SimpleDataBindingAdapter<CategoryModel, AdapterCategoryListBinding> {

    private final CategoryListFragment.OnFragmentInteractionListener listener;
    private String[] colorArray;

    public CategoryListAdapter(Context context, CategoryListFragment.OnFragmentInteractionListener onFragmentInteractionListener) {
        super(context, R.layout.adapter_category_list, new DiffUtil.ItemCallback<>() {
            @Override
            public boolean areItemsTheSame(@NonNull CategoryModel oldItem, @NonNull CategoryModel newItem) {
                return oldItem.getId().equals(newItem.getId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull CategoryModel oldItem, @NonNull CategoryModel newItem) {
                return oldItem.getName().equals(newItem.getName());
            }
        });

        this.listener = onFragmentInteractionListener;
        colorArray = context.getResources().getStringArray(R.array.ss_category_colors);

        setOnItemClickListener((item, position) -> listener.onListFragmentInteraction(item));
    }

    @Override
    protected void onBindItem(AdapterCategoryListBinding binding, CategoryModel item, RecyclerView.ViewHolder holder) {
        binding.setCategoryModel(item);
        if (binding.getAdapter() == null) {
            binding.setAdapter(this);
        }
    }

    public Drawable avatarColor(CategoryModel categoryModel) {

        String avatarName = categoryModel.getName().substring(0, 1);
        int color = Color.parseColor(colorArray[avatarName.hashCode() % colorArray.length]);
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(color);
        drawable.setShape(GradientDrawable.OVAL);
        return drawable;
    }
}
